package com.mmd.admin.model.pojo.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;

public class TokenCodec {

    private static final Log log = LogFactory.getLog(TokenCodec.class);

    private static final String ALGORITHM = "AES/CBC/PKCS5Padding"; // PKCS7Padding is not available in Java, use PKCS5Padding instead
    private static final byte[] INIT_VECTOR = hexStringToBytes("3a613563c433a361a62a9efe4dd8462e");

    public static String decrypt(String encryptedToken, String secret) {
        try {
            IvParameterSpec iv = new IvParameterSpec(INIT_VECTOR);
            SecretKeySpec skeySpec = new SecretKeySpec(secret.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

            byte[] original = cipher.doFinal(Base64.getDecoder().decode(encryptedToken));

            return new String(original);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 实现AES加密
     *
     * @param content
     * @param secret
     * @return
     */
    public static String encrypt(String content, String secret) {
        try {
            IvParameterSpec iv = new IvParameterSpec(INIT_VECTOR);
            SecretKeySpec skeySpec = new SecretKeySpec(secret.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            byte[] encrypted = cipher.doFinal(content.getBytes());
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }


    public static byte[] hexStringToBytes(String hexString) {
        byte[] destByte = new byte[hexString.length() / 2];
        int j = 0;
        for (int i = 0; i < destByte.length; i++) {
            byte high = (byte) (Character.digit(hexString.charAt(j), 16) & 0xff);
            byte low = (byte) (Character.digit(hexString.charAt(j + 1), 16) & 0xff);
            destByte[i] = (byte) (high << 4 | low);
            j += 2;
        }
        return destByte;
    }

    public static String getServeToken(Long storeId, String storeName, String storeCoverImgUrl, Long userId, String username, String userNick,String secret) {
        Calendar instance = Calendar.getInstance();
        instance.setTime(new Date());
        instance.add(Calendar.MONTH, 2);
        String token = JWT.create()
                .withClaim("storeId", storeId)
                .withClaim("storeName", storeName)
                .withClaim("storeCoverImgUrl", storeCoverImgUrl)
                .withClaim("userId", userId)
                .withClaim("username", username)
                .withClaim("userNick", userNick)
                .withClaim("userAvatar", storeCoverImgUrl)
                .withClaim("imUsername", username)
                .withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(secret));
//        String token = JWT.create()
//                .withClaim("storeId", storeId)
//                .withClaim("storeName", storeName)
//                .withClaim("storeCoverImgUrl", storeCoverImgUrl)
//                .withClaim("userId", userId)
//                .withClaim("username", username)
//                .withClaim("userNick", userNick)
//                .withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(secret));
        System.out.println("token: " + token);
        String encryptedToken = encrypt(token, secret);
        String decryptedToken = decrypt(encryptedToken, secret);
        String urlEncodedToken = URLEncoder.encode(encryptedToken);
        System.out.println("encryptedToken: " + encryptedToken);
        System.out.println("urlEncodedToken: " + urlEncodedToken);
        System.out.println("decryptedToken: " + decryptedToken);
        return urlEncodedToken;
    }


    public static String getServeTokenByStore(String storeId) {


        Calendar instance = Calendar.getInstance();
        instance.setTime(new Date());
        instance.add(Calendar.MONTH, 1);
        String secret = "rReeHtmQZSrJNim3";
        String token = JWT.create()
                .withClaim("storeId", storeId)
                .withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(secret));
        System.out.println("token: " + token);
        String encryptedToken = encrypt(token, secret);
        String decryptedToken = decrypt(encryptedToken, secret);
        String urlEncodedToken = URLEncoder.encode(encryptedToken);
        System.out.println("encryptedToken: " + encryptedToken);
        System.out.println("urlEncodedToken: " + urlEncodedToken);
        System.out.println("decryptedToken: " + decryptedToken);
        return encryptedToken;
    }

    public static void main(String[] args) {
        String serveTokenByStore = getServeTokenByStore("1");
    }


}
